#include "mainwindow.h"
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QWidget>
#include <QTimer>
#include <QProcess>
#include <QStringList>
#include <QRegularExpression>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <QMouseEvent>
#include <QScreen>
#include <QGuiApplication>
#include <QDesktopWidget>
#include <QStyle>
#include <QMenu>
#include <QAction>
#include <QPushButton>
#include <QDateTime>
#include <QSettings>
#include <QDir>  // 添加 QDir 头文件
#include <QLoggingCategory> // 新增：包含 QLogging 头文件以支持 qWarning() 和 qInfo()
#include <QTabWidget> // 添加标签页支持
#include <QTextEdit>  // 添加文本编辑器支持
#include <QScrollArea> // 添加滚动区域支持
#include <QFont>      // 添加字体支持
#include <QGroupBox>  // 添加分组框支持
#include <QFormLayout> // 添加表单布局支持
#include <QSpinBox>    // 添加数值选择框支持
#include <QCheckBox>   // 添加复选框支持
#include <QComboBox>   // 添加组合框支持
#include <QMessageBox> // 添加消息框支持
#include <QFileDialog> // 添加文件对话框支持
#include <QTextStream> // 添加文本流支持
#include <QTemporaryFile> // 添加 QTemporaryFile 头文件支持

// 添加以下行以解决 AutoMOC 错误
// #include "mainwindow.moc"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , settingsGroup(nullptr)
    , cpuUsageCheckBox(nullptr)
    , memoryCheckBox(nullptr)
    , swapCheckBox(nullptr)  // 初始化swapCheckBox
    , cpuFreqCheckBox(nullptr)
    , cpuMaxTempCheckBox(nullptr)
    , avgTempCheckBox(nullptr)
    , hddTempCheckBox(nullptr)
    , otherTempCheckBox(nullptr)
    , cpuLabel(nullptr)
    , memoryLabel(nullptr)
    , swapLabel(nullptr)  // 初始化swapLabel
    , temperatureLabel(nullptr)
    , floatingWindow(nullptr)
    , floatingCpuLabel(nullptr)
    , floatingMemoryLabel(nullptr)
    , floatingSwapLabel(nullptr)  // 初始化floatingSwapLabel
    , floatingCpuFreqLabel(nullptr)
    , floatingCpuMaxTempLabel(nullptr)
    , floatingAvgTempLabel(nullptr)
    , floatingHddTempLabel(nullptr)
    , floatingOtherTempLabel(nullptr)
    , trayIcon(nullptr)
    , m_resourceMonitor(new ResourceMonitor(this))  // 添加资源监控器实例
{
    // 从QSettings读取用户设置
    QSettings settings("linux-resource-monitor", "settings");
    currentSettings.cpuUsageEnabled = settings.value("cpuUsageEnabled", true).toBool();
    currentSettings.memoryEnabled = settings.value("memoryEnabled", true).toBool();
    currentSettings.swapEnabled = settings.value("swapEnabled", true).toBool();  // 添加swap设置
    currentSettings.cpuFreqEnabled = settings.value("cpuFreqEnabled", false).toBool();
    currentSettings.cpuMaxTempEnabled = settings.value("cpuMaxTempEnabled", false).toBool();
    currentSettings.avgTempEnabled = settings.value("avgTempEnabled", false).toBool();
    currentSettings.hddTempEnabled = settings.value("hddTempEnabled", false).toBool();
    currentSettings.otherTempEnabled = settings.value("otherTempEnabled", false).toBool();

    setupUI();
    setupMonitoring();
}

MainWindow::~MainWindow()
{
    // 清理系统托盘图标
    if (trayIcon) {
        trayIcon->hide();
        trayIcon = nullptr;
    }
    
    // 清理悬浮窗
    if (floatingWindow) {
        floatingWindow = nullptr;
    }
    
    // 保存用户设置
    QSettings settings("linux-resource-monitor", "settings");
    settings.setValue("cpuUsageEnabled", currentSettings.cpuUsageEnabled);
    settings.setValue("memoryEnabled", currentSettings.memoryEnabled);
    settings.setValue("swapEnabled", currentSettings.swapEnabled);
    settings.setValue("cpuFreqEnabled", currentSettings.cpuFreqEnabled);
    settings.setValue("cpuMaxTempEnabled", currentSettings.cpuMaxTempEnabled);
    settings.setValue("avgTempEnabled", currentSettings.avgTempEnabled);
    settings.setValue("hddTempEnabled", currentSettings.hddTempEnabled);
    settings.setValue("otherTempEnabled", currentSettings.otherTempEnabled);
}

void MainWindow::setupUI()
{
    setWindowTitle("Linux资源监控器");

    QTabWidget *tabWidget = new QTabWidget(this);
    setCentralWidget(tabWidget);

    // 创建系统资源监控页面
    QWidget *monitorWidget = createMonitorWidget();
    tabWidget->addTab(monitorWidget, "系统资源监控");

    // 创建CPU调度设置页面
    QWidget *schedulerWidget = createSchedulerWidget();
    tabWidget->addTab(schedulerWidget, "CPU调度设置");

    // 创建CPU调度日志页面
    QWidget *logWidget = createLogWidget();
    tabWidget->addTab(logWidget, "CPU调度日志");

    // 创建使用说明页面
    QWidget *helpWidget = createHelpWidget();
    tabWidget->addTab(helpWidget, "使用说明");

    // 添加定时器以定期更新监控数据
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]() {
        m_resourceMonitor->update();
        updateSystemInfo(); // 更新 UI 显示
    });
    timer->start(1000); // 每秒更新一次

    createSystemTrayIcon();
}

QWidget* MainWindow::createMonitorWidget()
{
    QWidget *monitorWidget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(monitorWidget);

    // 添加设置项勾选框
    settingsGroup = new QGroupBox("监控项设置", this);
    QVBoxLayout *settingsLayout = new QVBoxLayout(settingsGroup);

    cpuUsageCheckBox = new QCheckBox("CPU使用率", this);
    cpuUsageCheckBox->setChecked(currentSettings.cpuUsageEnabled);
    connect(cpuUsageCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.cpuUsageEnabled = checked;
        cpuLabel->setVisible(checked);
        if (floatingCpuLabel) floatingCpuLabel->setVisible(checked);
        updateSystemInfo(); // 触发数据更新
    });
    settingsLayout->addWidget(cpuUsageCheckBox);

    memoryCheckBox = new QCheckBox("内存使用率", this);
    memoryCheckBox->setChecked(currentSettings.memoryEnabled);
    connect(memoryCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.memoryEnabled = checked;
        memoryLabel->setVisible(checked);
        if (floatingMemoryLabel) floatingMemoryLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(memoryCheckBox);

    // 新增swap使用率勾选框
    swapCheckBox = new QCheckBox("Swap使用率", this);
    swapCheckBox->setChecked(currentSettings.swapEnabled);
    connect(swapCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.swapEnabled = checked;
        swapLabel->setVisible(checked);
        if (floatingSwapLabel) floatingSwapLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(swapCheckBox);

    cpuFreqCheckBox = new QCheckBox("CPU频率", this);
    cpuFreqCheckBox->setChecked(currentSettings.cpuFreqEnabled);
    connect(cpuFreqCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.cpuFreqEnabled = checked;
        cpuFreqLabel->setVisible(checked);
        if (floatingCpuFreqLabel) floatingCpuFreqLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(cpuFreqCheckBox);

    cpuMaxTempCheckBox = new QCheckBox("CPU最高温度", this);
    cpuMaxTempCheckBox->setChecked(currentSettings.cpuMaxTempEnabled);
    connect(cpuMaxTempCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.cpuMaxTempEnabled = checked;
        cpuMaxTempLabel->setVisible(checked);
        if (floatingCpuMaxTempLabel) floatingCpuMaxTempLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(cpuMaxTempCheckBox);

    avgTempCheckBox = new QCheckBox("平均温度", this);
    avgTempCheckBox->setChecked(currentSettings.avgTempEnabled);
    connect(avgTempCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.avgTempEnabled = checked;
        avgTempLabel->setVisible(checked);
        if (floatingAvgTempLabel) floatingAvgTempLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(avgTempCheckBox);

    hddTempCheckBox = new QCheckBox("硬盘温度", this);
    hddTempCheckBox->setChecked(currentSettings.hddTempEnabled);
    connect(hddTempCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.hddTempEnabled = checked;
        hddTempLabel->setVisible(checked);
        if (floatingHddTempLabel) floatingHddTempLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(hddTempCheckBox);

    otherTempCheckBox = new QCheckBox("其他硬件温度", this);
    otherTempCheckBox->setChecked(currentSettings.otherTempEnabled);
    connect(otherTempCheckBox, &QCheckBox::toggled, this, [this](bool checked){
        currentSettings.otherTempEnabled = checked;
        otherTempLabel->setVisible(checked);
        if (floatingOtherTempLabel) floatingOtherTempLabel->setVisible(checked);
        updateSystemInfo();
    });
    settingsLayout->addWidget(otherTempCheckBox);

    mainLayout->addWidget(settingsGroup);
    
    // 屏蔽悬浮窗控制按钮
    /*
    QPushButton *toggleFloatingBtn = new QPushButton("开启悬浮窗", this);
    toggleFloatingBtn->setCheckable(true);
    toggleFloatingBtn->setChecked(false); // 悬浮窗默认不开启
    connect(toggleFloatingBtn, &QPushButton::toggled, this, [this, toggleFloatingBtn](bool checked){
        if (floatingWindow) {
            floatingWindow->setVisible(checked);
            toggleFloatingBtn->setText(checked ? "关闭悬浮窗" : "开启悬浮窗");
        }
    });
    mainLayout->addWidget(toggleFloatingBtn);
    */

    // 创建悬浮窗
    createFloatingWindow();
    
    // 新增：创建监控数据信息显示区域
    QGroupBox *monitorDataGroup = new QGroupBox("监控数据信息", this);
    QVBoxLayout *monitorDataLayout = new QVBoxLayout(monitorDataGroup);

    cpuLabel = new QLabel("CPU使用率: --%", this);
    cpuLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    cpuLabel->setVisible(currentSettings.cpuUsageEnabled);
    cpuLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(cpuLabel);

    memoryLabel = new QLabel("内存使用率: --%", this);
    memoryLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    memoryLabel->setVisible(currentSettings.memoryEnabled);
    memoryLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(memoryLabel);

    // 添加Swap使用率标签
    swapLabel = new QLabel("Swap使用率: --%", this);
    swapLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    swapLabel->setVisible(currentSettings.swapEnabled);
    swapLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(swapLabel);

    // 添加CPU频率标签
    cpuFreqLabel = new QLabel("CPU频率: -- MHz", this);
    cpuFreqLabel->setObjectName("cpuFreqLabel");
    cpuFreqLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    cpuFreqLabel->setVisible(currentSettings.cpuFreqEnabled);
    cpuFreqLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(cpuFreqLabel);

    // 添加CPU最高温度标签
    cpuMaxTempLabel = new QLabel("CPU最高温度: --°C", this);
    cpuMaxTempLabel->setObjectName("cpuMaxTempLabel");
    cpuMaxTempLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    cpuMaxTempLabel->setVisible(currentSettings.cpuMaxTempEnabled);
    cpuMaxTempLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(cpuMaxTempLabel);

    // 添加平均温度标签
    avgTempLabel = new QLabel("平均温度: --°C", this);
    avgTempLabel->setObjectName("avgTempLabel");
    avgTempLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    avgTempLabel->setVisible(currentSettings.avgTempEnabled);
    avgTempLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(avgTempLabel);

    // 添加硬盘温度标签
    hddTempLabel = new QLabel("硬盘温度: --°C", this);
    hddTempLabel->setObjectName("hddTempLabel");
    hddTempLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    hddTempLabel->setVisible(currentSettings.hddTempEnabled);
    hddTempLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(hddTempLabel);

    // 添加其他硬件温度标签
    otherTempLabel = new QLabel("其他硬件温度: --°C", this);
    otherTempLabel->setObjectName("otherTempLabel");
    otherTempLabel->setStyleSheet("font-size: 16px; padding: 5px;");
    otherTempLabel->setVisible(currentSettings.otherTempEnabled);
    otherTempLabel->setAlignment(Qt::AlignLeft); // 统一左对齐
    monitorDataLayout->addWidget(otherTempLabel);

    mainLayout->addWidget(monitorDataGroup);
    
    // 添加占位符以填充布局
    mainLayout->addStretch();
    
    return monitorWidget;
}

QWidget* MainWindow::createSchedulerWidget()
{
    QWidget *schedulerWidget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(schedulerWidget);
    
    // 服务状态区域
    QGroupBox *statusGroup = new QGroupBox("服务状态");
    QHBoxLayout *statusLayout = new QHBoxLayout();
    QLabel *statusLabel = new QLabel("未知");
    statusLabel->setStyleSheet("QLabel { color : gray; font-weight: bold; }");
    statusLabel->setObjectName("schedulerStatusLabel");
    QPushButton *toggleButton = new QPushButton("启动服务");
    toggleButton->setObjectName("schedulerToggleButton");
    QPushButton *resetFreqButton = new QPushButton("恢复CPU最大频率");
    resetFreqButton->setObjectName("resetFreqButton");
    statusLayout->addWidget(new QLabel("状态:"));
    statusLayout->addWidget(statusLabel);
    statusLayout->addWidget(toggleButton);
    statusLayout->addWidget(resetFreqButton);
    statusLayout->addStretch();
    statusGroup->setLayout(statusLayout);
    mainLayout->addWidget(statusGroup);
    
    // 添加控制开关
    QGroupBox *controlGroup = new QGroupBox("控制选项");
    QHBoxLayout *controlLayout = new QHBoxLayout();
    
    QCheckBox *tempControlCheckbox = new QCheckBox("启用温度控制");
    tempControlCheckbox->setChecked(true);
    tempControlCheckbox->setObjectName("tempControlCheckbox");
    QCheckBox *freqControlCheckbox = new QCheckBox("启用频率控制");
    freqControlCheckbox->setChecked(true);
    freqControlCheckbox->setObjectName("freqControlCheckbox");
    controlLayout->addWidget(tempControlCheckbox);
    controlLayout->addWidget(freqControlCheckbox);
    controlLayout->addStretch();
    controlGroup->setLayout(controlLayout);
    mainLayout->addWidget(controlGroup);
    
    // 当前频率显示区域
    QGroupBox *freqGroup = new QGroupBox("当前状态");
    QHBoxLayout *freqLayout = new QHBoxLayout();
    QLabel *currentFreqLabel = new QLabel("当前频率: --%");
    currentFreqLabel->setObjectName("currentFreqLabel");
    QLabel *currentTempLabel = new QLabel("当前温度: --°C");
    currentTempLabel->setObjectName("currentTempLabel");
    QLabel *currentMaxFreqLabel = new QLabel("最大频率: --%");
    currentMaxFreqLabel->setObjectName("currentMaxFreqLabel");
    freqLayout->addWidget(currentFreqLabel);
    freqLayout->addWidget(currentTempLabel);
    freqLayout->addWidget(currentMaxFreqLabel);
    freqGroup->setLayout(freqLayout);
    mainLayout->addWidget(freqGroup);
    
    // 配置区域
    QFormLayout *configLayout = new QFormLayout();
    
    // 检查间隔
    QSpinBox *intervalSpin = new QSpinBox();
    intervalSpin->setRange(1, 300);
    intervalSpin->setValue(10);
    intervalSpin->setObjectName("intervalSpin");
    configLayout->addRow("检查间隔(秒):", intervalSpin);
    
    // 高频率阈值
    QSpinBox *highFreqSpin = new QSpinBox();
    highFreqSpin->setRange(10, 100);
    highFreqSpin->setValue(80);
    highFreqSpin->setSuffix("%");
    highFreqSpin->setObjectName("highFreqSpin");
    configLayout->addRow("高频率阈值:", highFreqSpin);
    
    // 低频率阈值
    QSpinBox *lowFreqSpin = new QSpinBox();
    lowFreqSpin->setRange(10, 100);
    lowFreqSpin->setValue(40);
    lowFreqSpin->setSuffix("%");
    lowFreqSpin->setObjectName("lowFreqSpin");
    configLayout->addRow("低频率阈值:", lowFreqSpin);
    
    // 高温度阈值
    QSpinBox *highTempSpin = new QSpinBox();
    highTempSpin->setRange(50, 100);
    highTempSpin->setValue(60);
    highTempSpin->setSuffix("°C");
    highTempSpin->setObjectName("highTempSpin");
    configLayout->addRow("高温度阈值:", highTempSpin);
    
    // 低温度阈值
    QSpinBox *lowTempSpin = new QSpinBox();
    lowTempSpin->setRange(30, 80);
    lowTempSpin->setValue(40);
    lowTempSpin->setSuffix("°C");
    lowTempSpin->setObjectName("lowTempSpin");
    configLayout->addRow("低温度阈值:", lowTempSpin);
    
    // 持续时间
    QSpinBox *sustainedSpin = new QSpinBox();
    sustainedSpin->setRange(10, 600);
    sustainedSpin->setValue(60);
    sustainedSpin->setObjectName("sustainedSpin");
    configLayout->addRow("持续时间阈值(秒):", sustainedSpin);
    
    // 频率调整幅度
    QHBoxLayout *adjustmentLayout = new QHBoxLayout();
    QSpinBox *reductionSpin = new QSpinBox();
    reductionSpin->setRange(5, 50);
    reductionSpin->setValue(25);
    reductionSpin->setSingleStep(5);
    reductionSpin->setSuffix("%");
    reductionSpin->setObjectName("reductionSpin");
    QSpinBox *increaseSpin = new QSpinBox();
    increaseSpin->setRange(5, 50);
    increaseSpin->setValue(25);
    increaseSpin->setSingleStep(5);
    increaseSpin->setSuffix("%");
    increaseSpin->setObjectName("increaseSpin");
    adjustmentLayout->addWidget(reductionSpin);
    adjustmentLayout->addWidget(increaseSpin);
    configLayout->addRow("频率调整幅度(降/升):", adjustmentLayout);
    
    // 添加最低频率限制配置项
    QSpinBox *minFreqLimitSpin = new QSpinBox();
    minFreqLimitSpin->setRange(50, 95);
    minFreqLimitSpin->setValue(50);
    minFreqLimitSpin->setSingleStep(5);
    minFreqLimitSpin->setSuffix("%");
    minFreqLimitSpin->setObjectName("minFreqLimitSpin");
    configLayout->addRow("最低频率限制:", minFreqLimitSpin);
    
    QGroupBox *configGroup = new QGroupBox("配置参数");
    configGroup->setLayout(configLayout);
    mainLayout->addWidget(configGroup);
    
    // 操作按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *applyButton = new QPushButton("应用配置");
    applyButton->setObjectName("applyButton");
    QPushButton *resetButton = new QPushButton("恢复默认");
    resetButton->setObjectName("resetButton");
    QPushButton *saveButton = new QPushButton("保存配置");
    saveButton->setObjectName("saveButton");
    
    QLabel *buttonHelp = new QLabel("说明: 应用配置(重启服务) | 恢复默认(重置参数为默认并重启服务应用配置) | 保存配置(仅保存)");
    buttonHelp->setStyleSheet("QLabel { color : gray; font-size : 10pt; }");
    
    buttonLayout->addWidget(applyButton);
    buttonLayout->addWidget(resetButton);
    buttonLayout->addWidget(saveButton);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(buttonHelp);
    
    // 连接信号槽
    connect(toggleButton, &QPushButton::clicked, this, [this, statusLabel, toggleButton]() {
        toggleSchedulerService(statusLabel, toggleButton);
    });
    
    connect(resetFreqButton, &QPushButton::clicked, this, &MainWindow::resetCpuFrequency);
    
    connect(applyButton, &QPushButton::clicked, this, [this, intervalSpin, highFreqSpin, lowFreqSpin,
            highTempSpin, lowTempSpin, sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
            tempControlCheckbox, freqControlCheckbox]() {
        applySchedulerConfig(intervalSpin, highFreqSpin, lowFreqSpin, highTempSpin, lowTempSpin,
                            sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
                            tempControlCheckbox, freqControlCheckbox);
    });
    
    connect(resetButton, &QPushButton::clicked, this, [this, intervalSpin, highFreqSpin, lowFreqSpin,
            highTempSpin, lowTempSpin, sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
            tempControlCheckbox, freqControlCheckbox]() {
        resetSchedulerConfig(intervalSpin, highFreqSpin, lowFreqSpin, highTempSpin, lowTempSpin,
                            sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
                            tempControlCheckbox, freqControlCheckbox);
    });
    
    connect(saveButton, &QPushButton::clicked, this, [this, intervalSpin, highFreqSpin, lowFreqSpin,
            highTempSpin, lowTempSpin, sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
            tempControlCheckbox, freqControlCheckbox]() {
        saveSchedulerConfig(intervalSpin, highFreqSpin, lowFreqSpin, highTempSpin, lowTempSpin,
                            sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
                            tempControlCheckbox, freqControlCheckbox);
    });
    
    // 定时刷新服务状态
    QTimer *statusTimer = new QTimer(this);
    connect(statusTimer, &QTimer::timeout, this, [this, statusLabel, toggleButton]() {
        updateSchedulerStatus(statusLabel, toggleButton);
    });
    statusTimer->start(5000); // 每5秒检查一次
    updateSchedulerStatus(statusLabel, toggleButton); // 立即检查一次
    
    return schedulerWidget;
}

QWidget* MainWindow::createLogWidget()
{
    QWidget *logWidget = new QWidget();
    QVBoxLayout *logLayout = new QVBoxLayout(logWidget);
    
    // 日志显示区域
    QGroupBox *logGroup = new QGroupBox("服务日志");
    QVBoxLayout *logLayoutInner = new QVBoxLayout();
    QTextEdit *logText = new QTextEdit();
    logText->setReadOnly(true);
    logText->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
    logText->setContextMenuPolicy(Qt::DefaultContextMenu);
    logText->setLineWrapMode(QTextEdit::NoWrap);
    logLayoutInner->addWidget(logText);

    QHBoxLayout *logButtonLayout = new QHBoxLayout();
    QPushButton *clearLogButton = new QPushButton("清空日志");
    QPushButton *refreshLogButton = new QPushButton("刷新日志");
    logButtonLayout->addWidget(clearLogButton);
    logButtonLayout->addWidget(refreshLogButton);
    logLayoutInner->addLayout(logButtonLayout);
    
    logGroup->setLayout(logLayoutInner);
    logLayout->addWidget(logGroup);
    
    return logWidget;
}

QWidget* MainWindow::createHelpWidget()
{
    QWidget *helpWidget = new QWidget();
    QVBoxLayout *helpLayout = new QVBoxLayout(helpWidget);
    
    // 创建滚动区域以容纳长内容
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    helpLayout->addWidget(scrollArea);
    
    // 创建内容区域
    QWidget *contentWidget = new QWidget();
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
    
    // 添加标题
    QLabel *titleLabel = new QLabel("Linux资源监控器使用说明");
    QFont titleFont;
    titleFont.setPointSize(16);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    titleLabel->setAlignment(Qt::AlignCenter);
    contentLayout->addWidget(titleLabel);
    
    // 添加功能介绍
    QGroupBox *funcGroup = new QGroupBox("功能介绍");
    QVBoxLayout *funcLayout = new QVBoxLayout();
    QTextEdit *funcText = new QTextEdit();
    funcText->setReadOnly(true);
    funcText->setHtml(R"(
    <p>Linux资源监控器是一个综合性的系统监控工具，主要功能包括：</p>
    <ul>
    <li>实时监控系统资源使用情况（CPU、内存、Swap等）</li>
    <li>监控硬件温度（CPU、硬盘等）</li>
    <li>动态调整CPU频率以优化性能和功耗</li>
    <li>防止CPU过热，提高系统稳定性</li>
    <li>提供悬浮窗和系统托盘显示</li>
    <li>详细的日志记录功能</li>
    </ul>
    )");
    funcLayout->addWidget(funcText);
    funcGroup->setLayout(funcLayout);
    contentLayout->addWidget(funcGroup);
    
    // 添加工作原理
    QGroupBox *principleGroup = new QGroupBox("工作原理");
    QVBoxLayout *principleLayout = new QVBoxLayout();
    QTextEdit *principleText = new QTextEdit();
    principleText->setReadOnly(true);
    principleText->setHtml(R"(
    <p>Linux资源监控器通过以下方式工作：</p>
    <ol>
    <li>定期检查系统资源使用情况和硬件温度</li>
    <li>当检测到持续高负载或高温时，自动调整CPU频率</li>
    <li>当负载或温度降低并持续一段时间后，恢复CPU频率</li>
    <li>所有调整都在安全范围内进行，确保系统正常运行</li>
    </ol>
    <p>调度器使用以下两个主要控制机制：</p>
    <ul>
    <li><b>温度控制：</b>当CPU温度超过设定阈值并持续一定时间时，降低CPU频率以减少发热</li>
    <li><b>频率控制：</b>当CPU使用率持续过高时，主动降低频率以防止长时间睿频</li>
    </ul>
    )");
    principleLayout->addWidget(principleText);
    principleGroup->setLayout(principleLayout);
    contentLayout->addWidget(principleGroup);
    
    // 添加界面说明
    QGroupBox *interfaceGroup = new QGroupBox("界面说明");
    QVBoxLayout *interfaceLayout = new QVBoxLayout();
    QTextEdit *interfaceText = new QTextEdit();
    interfaceText->setReadOnly(true);
    interfaceText->setHtml(R"(
    <p>主界面包含四个标签页：</p>
    <ul>
    <li><b>系统资源监控：</b>显示当前系统资源使用情况，可设置监控项</li>
    <li><b>CPU调度设置：</b>配置CPU频率调度参数</li>
    <li><b>CPU调度日志：</b>查看调度器运行日志</li>
    <li><b>使用说明：</b>查看软件使用帮助和信息</li>
    </ul>
    <p>监控项设置说明：</p>
    <ul>
    <li><b>CPU使用率：</b>显示CPU使用百分比</li>
    <li><b>内存使用率：</b>显示内存使用百分比</li>
    <li><b>Swap使用率：</b>显示Swap使用百分比</li>
    <li><b>CPU频率：</b>显示当前CPU频率</li>
    <li><b>CPU最高温度：</b>显示CPU最高温度</li>
    <li><b>平均温度：</b>显示系统平均温度</li>
    <li><b>硬盘温度：</b>显示硬盘温度</li>
    <li><b>其他硬件温度：</b>显示其他硬件温度</li>
    </ul>
    )");
    interfaceLayout->addWidget(interfaceText);
    interfaceGroup->setLayout(interfaceLayout);
    contentLayout->addWidget(interfaceGroup);
    
    // 添加文件路径说明
    QGroupBox *filesGroup = new QGroupBox("文件路径说明");
    QVBoxLayout *filesLayout = new QVBoxLayout();
    QTextEdit *filesText = new QTextEdit();
    filesText->setReadOnly(true);
    filesText->setHtml(R"(
    <p>本程序使用以下重要文件和目录：</p>
    <ul>
    <li><b>配置文件：</b>/etc/cpu-scheduler.conf</li>
    <li><b>日志文件：</b>/var/log/cpu-scheduler.log</li>
    <li><b>服务文件：</b>/etc/systemd/system/cpu-scheduler.service</li>
    <li><b>主程序：</b>/usr/local/bin/cpu_scheduler</li>
    </ul>
    )");
    filesLayout->addWidget(filesText);
    filesGroup->setLayout(filesLayout);
    contentLayout->addWidget(filesGroup);
    
    // 添加使用建议
    QGroupBox *tipsGroup = new QGroupBox("使用建议");
    QVBoxLayout *tipsLayout = new QVBoxLayout();
    QTextEdit *tipsText = new QTextEdit();
    tipsText->setReadOnly(true);
    tipsText->setHtml(R"(
    <p>为了更好地使用Linux资源监控器，建议：</p>
    <ul>
    <li>根据您的CPU型号和散热条件调整温度阈值</li>
    <li>在需要高性能的场景中，可以临时调整频率控制参数</li>
    <li>定期查看日志标签页，了解调度器的工作情况</li>
    <li>如发现系统性能问题，可适当调整相关参数</li>
    <li>在不需要时可以停止服务以减少系统资源占用</li>
    </ul>
    <p>注意事项：</p>
    <ul>
    <li>修改配置后需要重启服务才能生效</li>
    <li>某些功能需要root权限才能操作</li>
    <li>请勿将频率调整幅度设置得过大，以免影响系统稳定性</li>
    <li>当CPU频率已经小于或等于50%时，为避免系统性能过低，即使检测到高温或高频率情况也不会进一步降低频率</li>
    <li>日志文件会自动清理，如需保留长期日志请定期备份</li>
    </ul>
    )");
    tipsLayout->addWidget(tipsText);
    tipsGroup->setLayout(tipsLayout);
    contentLayout->addWidget(tipsGroup);
    
    // 添加作者信息和网站地址
    QGroupBox *infoGroup = new QGroupBox("关于");
    QVBoxLayout *infoLayout = new QVBoxLayout();
    QTextEdit *infoText = new QTextEdit();
    infoText->setReadOnly(true);
    infoText->setHtml(R"(
    <p><b>作者:</b> 洗衣带娃 （a343025902@qq.com）</p>
    <p><b>创意:</b> fslong （https://atomgit.com/fslong/kernel_config）</p>
    <p><b>项目网站:</b> https://gitee.com/gys1987/linux-resource-monitor </p>
    <p><b>版本:</b> 1.1.20</p>
    )");
    infoLayout->addWidget(infoText);
    infoGroup->setLayout(infoLayout);
    contentLayout->addWidget(infoGroup);
    
    // 设置滚动区域内容
    scrollArea->setWidget(contentWidget);
    
    return helpWidget;
}

void MainWindow::createFloatingWindow()
{
    // 创建悬浮窗
    floatingWindow = new QWidget(nullptr, Qt::ToolTip | Qt::WindowStaysOnTopHint);
    floatingWindow->setWindowTitle("系统监控");
    floatingWindow->setFixedSize(250, 180); // 增大窗口尺寸以容纳更多信息
    floatingWindow->setStyleSheet("background-color: rgba(0, 0, 0, 160); color: white; border-radius: 8px;");
    floatingWindow->setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    
    // 创建悬浮窗布局
    QVBoxLayout *layout = new QVBoxLayout(floatingWindow);
    layout->setContentsMargins(10, 10, 10, 10);
    
    // 创建悬浮窗标签
    QLabel *titleLabel = new QLabel("系统资源监控", floatingWindow);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-weight: bold; font-size: 12px; color: white;");
    
    // 添加CPU使用率
    floatingCpuLabel = new QLabel("CPU: --%", floatingWindow);
    floatingCpuLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingCpuLabel->setVisible(currentSettings.cpuUsageEnabled);
    
    // 添加内存使用率
    floatingMemoryLabel = new QLabel("内存: --%", floatingWindow); // 新增内存标签
    floatingMemoryLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingMemoryLabel->setVisible(currentSettings.memoryEnabled);
    
    // 添加Swap使用率到悬浮窗
    floatingSwapLabel = new QLabel("Swap: --%", floatingWindow);
    floatingSwapLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingSwapLabel->setVisible(currentSettings.swapEnabled);
    
    // 添加CPU频率
    floatingCpuFreqLabel = new QLabel("CPU Freq: -- MHz", floatingWindow);
    floatingCpuFreqLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingCpuFreqLabel->setVisible(currentSettings.cpuFreqEnabled);
    
    // 添加CPU最高温度
    floatingCpuMaxTempLabel = new QLabel("CPU Max Temp: --°C", floatingWindow);
    floatingCpuMaxTempLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingCpuMaxTempLabel->setVisible(currentSettings.cpuMaxTempEnabled);
    
    // 添加平均温度
    floatingAvgTempLabel = new QLabel("Avg Temp: --°C", floatingWindow);
    floatingAvgTempLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingAvgTempLabel->setVisible(currentSettings.avgTempEnabled);
    
    // 添加硬盘温度
    floatingHddTempLabel = new QLabel("HDD Temp: --°C", floatingWindow);
    floatingHddTempLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingHddTempLabel->setVisible(currentSettings.hddTempEnabled);
    
    // 添加其他硬件温度
    floatingOtherTempLabel = new QLabel("Other Temp: --°C", floatingWindow);
    floatingOtherTempLabel->setStyleSheet("color: white; font-size: 10px;");
    floatingOtherTempLabel->setVisible(currentSettings.otherTempEnabled);
    
    layout->addWidget(titleLabel);
    layout->addWidget(floatingCpuLabel);
    layout->addWidget(floatingMemoryLabel); // 添加内存标签
    layout->addWidget(floatingSwapLabel);
    layout->addWidget(floatingCpuFreqLabel);
    layout->addWidget(floatingCpuMaxTempLabel);
    layout->addWidget(floatingAvgTempLabel);
    layout->addWidget(floatingHddTempLabel);
    layout->addWidget(floatingOtherTempLabel);
    
    // 设置悬浮窗位置到右下角
    QRect screenGeometry = QGuiApplication::primaryScreen()->geometry();
    floatingWindow->move(screenGeometry.width() - 270, screenGeometry.height() - 200);
    
    // 默认隐藏悬浮窗
    floatingWindow->hide();
    
    // 添加事件过滤器以支持拖拽
    floatingWindow->installEventFilter(this);
    
    // 连接定时器更新悬浮窗数据
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateFloatingWindow);
    timer->start(1000);
}

void MainWindow::updateSystemInfo()
{
    // 统一计算所有监控数据
    cachedCpuUsage = getCpuUsage();
    cachedMemoryUsage = getMemoryUsage();
    cachedSwapUsage = getSwapUsage();  // 确保获取Swap使用率
    cachedCpuFreq = getCpuFrequency(); // 修复：使用正确的函数调用
    cachedCpuMaxTemp = getCPUMaxTemperature();
    cachedAvgTemp = getAverageTemperature();
    cachedHddTemp = getHDDTemperature();
    cachedOtherTemp = getOtherHardwareTemperature();

    // 更新主窗口标签
    cpuLabel->setText(QString("CPU使用率: %1%").arg(QString::number(cachedCpuUsage, 'f', 1)));
    memoryLabel->setText(QString("内存使用率: %1%").arg(QString::number(cachedMemoryUsage, 'f', 1)));
    swapLabel->setText(QString("Swap使用率: %1%").arg(QString::number(cachedSwapUsage, 'f', 1)));  // 确保更新Swap标签
    cpuFreqLabel->setText(QString("CPU频率: %1 MHz").arg(cachedCpuFreq));
    cpuMaxTempLabel->setText(QString("CPU最高温度: %1°C").arg(cachedCpuMaxTemp));
    avgTempLabel->setText(QString("平均温度: %1°C").arg(cachedAvgTemp));
    hddTempLabel->setText(QString("硬盘温度: %1°C").arg(cachedHddTemp));
    otherTempLabel->setText(QString("其他硬件温度: %1°C").arg(cachedOtherTemp));

    // 更新悬浮窗信息
    if (floatingWindow && floatingWindow->isVisible()) {
        updateFloatingWindow();
    }
    
    // 更新系统托盘图标信息
    updateSystemTrayIcon();
}

void MainWindow::updateFloatingWindow()
{
    if (!floatingWindow || !floatingWindow->isVisible()) return;
    
    // 使用缓存的数据，避免重复计算
    floatingCpuLabel->setText(QString("CPU: %1%").arg(QString::number(cachedCpuUsage, 'f', 1)));
    floatingCpuLabel->setVisible(currentSettings.cpuUsageEnabled);
    
    floatingMemoryLabel->setText(QString("内存: %1%").arg(QString::number(cachedMemoryUsage, 'f', 1)));
    floatingMemoryLabel->setVisible(currentSettings.memoryEnabled);
    
    floatingSwapLabel->setText(QString("Swap: %1%").arg(QString::number(cachedSwapUsage, 'f', 1)));  // 新增：更新Swap标签
    floatingSwapLabel->setVisible(currentSettings.swapEnabled);
    
    floatingCpuFreqLabel->setText(QString("CPU Freq: %1 MHz").arg(cachedCpuFreq));
    floatingCpuFreqLabel->setVisible(currentSettings.cpuFreqEnabled);
    
    floatingCpuMaxTempLabel->setText(QString("CPU Max Temp: %1°C").arg(cachedCpuMaxTemp));
    floatingCpuMaxTempLabel->setVisible(currentSettings.cpuMaxTempEnabled);
    
    floatingAvgTempLabel->setText(QString("Avg Temp: %1°C").arg(cachedAvgTemp));
    floatingAvgTempLabel->setVisible(currentSettings.avgTempEnabled);
    
    floatingHddTempLabel->setText(QString("HDD Temp: %1°C").arg(cachedHddTemp));
    floatingHddTempLabel->setVisible(currentSettings.hddTempEnabled);
    
    floatingOtherTempLabel->setText(QString("Other Temp: %1°C").arg(cachedOtherTemp));
    floatingOtherTempLabel->setVisible(currentSettings.otherTempEnabled);
    
    // 更新工具提示
    QString tooltipText = QString("CPU: %1%\nCPU Freq: %2 MHz\nCPU Max Temp: %3°C\nAvg Temp: %4°C\nHDD Temp: %5°C\nOther Temp: %6°C\n内存: %7%\nSwap: %8%")
                          .arg(QString::number(cachedCpuUsage, 'f', 2))
                          .arg(cachedCpuFreq)
                          .arg(cachedCpuMaxTemp)
                          .arg(cachedAvgTemp)
                          .arg(cachedHddTemp)
                          .arg(cachedOtherTemp)
                          .arg(QString::number(cachedMemoryUsage, 'f', 2))
                          .arg(QString::number(cachedSwapUsage, 'f', 2));  // 新增：添加Swap到tooltip
    floatingWindow->setToolTip(tooltipText);
}

void MainWindow::updateSystemTrayIcon()
{
    if (!trayIcon) return;
    
    // 使用缓存的数据，避免重复计算
    QString tooltip = "系统资源监控\n";
    
    // 根据设置添加CPU使用率
    if (currentSettings.cpuUsageEnabled) {
        tooltip += QString("CPU: %1%\n").arg(QString::number(cachedCpuUsage, 'f', 1));
    }
    
    // 根据设置添加内存使用率
    if (currentSettings.memoryEnabled) {
        tooltip += QString("内存: %1%\n").arg(QString::number(cachedMemoryUsage, 'f', 1));
    }
    
    // 根据设置添加Swap使用率
    if (currentSettings.swapEnabled) {
        tooltip += QString("Swap: %1%\n").arg(QString::number(cachedSwapUsage, 'f', 1));
    }
    
    // 根据设置添加CPU频率
    if (currentSettings.cpuFreqEnabled) {
        tooltip += QString("CPU Freq: %1 MHz\n").arg(cachedCpuFreq);
    }
    
    // 根据设置添加CPU最高温度
    if (currentSettings.cpuMaxTempEnabled) {
        tooltip += QString("CPU Max Temp: %1°C\n").arg(cachedCpuMaxTemp);
    }
    
    // 根据设置添加平均温度
    if (currentSettings.avgTempEnabled) {
        tooltip += QString("Avg Temp: %1°C\n").arg(cachedAvgTemp);
    }
    
    // 根据设置添加硬盘温度
    if (currentSettings.hddTempEnabled) {
        tooltip += QString("HDD Temp: %1°C\n").arg(cachedHddTemp);
    }
    
    // 根据设置添加其他硬件温度
    if (currentSettings.otherTempEnabled) {
        tooltip += QString("Other Temp: %1°C\n").arg(cachedOtherTemp);
    }
    
    // 移除最后一个换行符
    if (!tooltip.isEmpty()) {
        tooltip.chop(1);
    }
    
    trayIcon->setToolTip(tooltip);

    // 设置托盘图标
    QString iconPath = QDir(QApplication::applicationDirPath()).absoluteFilePath("../share/icons/hicolor/48x48/apps/linux-resource-monitor.png");
    if (QFile::exists(iconPath)) {
        trayIcon->setIcon(QIcon(iconPath));
    } else {
        trayIcon->setIcon(QIcon()); // 使用空图标
    }
}

void MainWindow::setupMonitoring()
{
    // 创建定时器，每1秒更新一次数据
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateSystemInfo);
    timer->start(1000);
    
    // 立即更新一次
    updateSystemInfo();
}

double MainWindow::getCpuUsage()
{
    static unsigned long long lastTotal = 0;
    static unsigned long long lastIdle = 0;
    
    std::ifstream file("/proc/stat");
    std::string line;
    
    if (std::getline(file, line)) {
        std::istringstream ss(line);
        std::string cpuLabel;
        unsigned long long user, nice, system, idle, iowait, irq, softirq, steal;
        
        ss >> cpuLabel >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal;
        
        unsigned long long currentIdle = idle + iowait;
        unsigned long long currentTotal = user + nice + system + idle + iowait + irq + softirq + steal;
        
        if (lastTotal != 0) {
            unsigned long long totalDiff = currentTotal - lastTotal;
            unsigned long long idleDiff = currentIdle - lastIdle;
            
            double cpuUsage = 100.0 * (totalDiff - idleDiff) / totalDiff;
            
            lastTotal = currentTotal;
            lastIdle = currentIdle;
            
            return cpuUsage;
        }
        
        lastTotal = currentTotal;
        lastIdle = currentIdle;
    }
    
    return 0.0;
}

int MainWindow::getCpuFrequency()
{
    // 读取CPU频率信息
    QFile file("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
    if (file.open(QIODevice::ReadOnly)) {
        QString content = file.readAll().trimmed();
        file.close();
        
        bool ok;
        int currentFreq = content.toInt(&ok);
        if (ok) {
            // 直接返回MHz值，不需要转换为百分比
            return currentFreq / 1000; // 转换为MHz
        }
    }
    
    // 如果无法读取实际频率，返回模拟数据
    return 90; // 默认返回90MHz（与图片中的值一致）
}

double MainWindow::getMemoryUsage()
{
    std::ifstream file("/proc/meminfo");
    std::string line;
    long long memTotal = 0;
    long long memAvailable = 0;
    
    while (std::getline(file, line)) {
        if (line.substr(0, 8) == "MemTotal") {
            std::istringstream ss(line);
            std::string label;
            ss >> label >> memTotal;
        } else if (line.substr(0, 12) == "MemAvailable") {
            std::istringstream ss(line);
            std::string label;
            ss >> label >> memAvailable;
            break;
        }
    }
    
    if (memTotal > 0) {
        return 100.0 * (memTotal - memAvailable) / memTotal;
    }
    
    return 0.0;
}

double MainWindow::getSwapUsage()
{
    std::ifstream file("/proc/meminfo");
    if (!file.is_open()) {
        qWarning() << "Failed to open /proc/meminfo for swap usage";
        return 0.0;
    }

    std::string line;
    long long swapTotal = 0;
    long long swapFree = 0;

    while (std::getline(file, line)) {
        // 使用正则表达式或更安全的字符串查找
        if (line.find("SwapTotal:") != std::string::npos) {
            std::istringstream ss(line);
            std::string label;
            ss >> label; // 跳过 "SwapTotal:"
            ss >> swapTotal;
            qInfo() << "SwapTotal:" << swapTotal;
        } else if (line.find("SwapFree:") != std::string::npos) {
            std::istringstream ss(line);
            std::string label;
            ss >> label; // 跳过 "SwapFree:"
            ss >> swapFree;
            qInfo() << "SwapFree:" << swapFree;
            break;
        }
    }

    if (swapTotal > 0) {
        double usage = 100.0 * (swapTotal - swapFree) / swapTotal;
        qInfo() << "Swap usage calculated:" << usage << "% (Total:" << swapTotal << " Free:" << swapFree << ")";
        return usage;
    }

    qWarning() << "No valid swap data found in /proc/meminfo";
    return 0.0;
}

double MainWindow::getTemperature()
{
    // 尝试从多个可能的温度文件中读取
    const char* tempFiles[] = {
        "/sys/class/thermal/thermal_zone0/temp",
        "/sys/class/hwmon/hwmon0/temp1_input",
        "/sys/class/hwmon/hwmon1/temp1_input",
        "/sys/class/hwmon/hwmon2/temp1_input"
    };
    
    for (const char* tempFile : tempFiles) {
        std::ifstream file(tempFile);
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line);
                    return temp / 1000.0; // 转换为摄氏度
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    return 0.0;
}

// 实现获取CPU最高温度的函数
int MainWindow::getCPUMaxTemperature()
{
    int maxTemp = 0;
    bool found = false;
    
    // 遍历所有thermal_zone目录
    for (int i = 0; i < 10; i++) {
        QString tempPath = QString("/sys/class/thermal/thermal_zone%1/temp").arg(i);
        std::ifstream file(tempPath.toStdString());
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line) / 1000; // 转换为摄氏度
                    if (!found || temp > maxTemp) {
                        maxTemp = temp;
                        found = true;
                    }
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    // 同时检查hwmon目录
    for (int i = 0; i < 10; i++) {
        QString tempPath = QString("/sys/class/hwmon/hwmon%1/temp1_input").arg(i);
        std::ifstream file(tempPath.toStdString());
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line) / 1000; // 转换为摄氏度
                    if (!found || temp > maxTemp) {
                        maxTemp = temp;
                        found = true;
                    }
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    return found ? maxTemp : static_cast<int>(getTemperature()) + 5;
}

// 实现获取平均温度的函数
int MainWindow::getAverageTemperature()
{
    int totalTemp = 0;
    int count = 0;
    
    // 遍历所有thermal_zone目录
    for (int i = 0; i < 10; i++) {
        QString tempPath = QString("/sys/class/thermal/thermal_zone%1/temp").arg(i);
        std::ifstream file(tempPath.toStdString());
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line) / 1000; // 转换为摄氏度
                    totalTemp += temp;
                    count++;
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    // 同时检查hwmon目录
    for (int i = 0; i < 10; i++) {
        QString tempPath = QString("/sys/class/hwmon/hwmon%1/temp1_input").arg(i);
        std::ifstream file(tempPath.toStdString());
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line) / 1000; // 转换为摄氏度
                    totalTemp += temp;
                    count++;
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    if (count > 0) {
        return totalTemp / count;
    }
    
    return static_cast<int>(getTemperature()) - 2;
}

// 实现获取硬盘温度的函数
int MainWindow::getHDDTemperature()
{
    // 首先尝试使用smartctl命令获取硬盘温度
    QProcess process;
    process.start("smartctl", QStringList() << "-A" << "/dev/sda");
    process.waitForFinished(3000); // 等待最多3秒
    
    if (process.exitCode() == 0) {
        QString output = process.readAllStandardOutput();
        QStringList lines = output.split('\n');
        
        // 查找温度行
        for (const QString &line : lines) {
            if (line.contains("Temperature_Celsius", Qt::CaseInsensitive) || 
                line.contains("Airflow_Temperature_Cel", Qt::CaseInsensitive)) {
                QStringList parts = line.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
                if (parts.size() >= 10) {
                    bool ok;
                    int temp = parts[9].toInt(&ok);
                    if (ok) {
                        return temp;
                    }
                }
            }
        }
    }
    
    // 如果smartctl不可用或失败，尝试从系统文件读取
    const char* hddTempFiles[] = {
        "/sys/class/hwmon/hwmon0/temp1_input",
        "/sys/class/hwmon/hwmon1/temp1_input",
        "/sys/class/hwmon/hwmon2/temp1_input",
        "/sys/class/hwmon/hwmon3/temp1_input"
    };
    
    for (const char* tempFile : hddTempFiles) {
        std::ifstream file(tempFile);
        if (file.is_open()) {
            std::string line;
            if (std::getline(file, line)) {
                try {
                    int temp = std::stoi(line) / 1000; // 转换为摄氏度
                    // 硬盘温度通常比CPU温度低，如果读取的温度在合理范围内，则认为是硬盘温度
                    if (temp > 0 && temp < 100) {
                        return temp;
                    }
                } catch (...) {
                    continue;
                }
            }
        }
    }
    
    // 回退到模拟数据
    return static_cast<int>(getTemperature()) - 3;
}

int MainWindow::getOtherHardwareTemperature()
{
    // 模拟：返回当前温度+2
    return static_cast<int>(getTemperature()) + 2;
}

void MainWindow::createSystemTrayIcon()
{
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        return;
    }
    
    trayIcon = new QSystemTrayIcon(this);
    
    // 使用应用程序图标作为系统托盘图标
    QString iconPath = QDir(QApplication::applicationDirPath()).absoluteFilePath("../share/icons/hicolor/48x48/apps/linux-resource-monitor.png");
    if (QFile::exists(iconPath)) {
        trayIcon->setIcon(QIcon(iconPath));
    } else {
        // 如果图标文件不存在，创建一个空图标而不是使用不存在的资源
        trayIcon->setIcon(QIcon()); // 使用空图标
    }
    
    // 创建托盘菜单
    QMenu *trayMenu = new QMenu(this);
    QAction *restoreAction = new QAction("显示主窗口", this);
    QAction *quitAction = new QAction("退出", this);
    
    connect(restoreAction, &QAction::triggered, this, &MainWindow::showNormal);
    connect(quitAction, &QAction::triggered, this, &MainWindow::quitApplication);
    
    trayMenu->addAction(restoreAction);
    trayMenu->addSeparator();
    trayMenu->addAction(quitAction);
    
    trayIcon->setContextMenu(trayMenu);
    
    // 连接系统托盘图标的激活信号
    connect(trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::iconActivated);
    
    trayIcon->show();
}

// 添加退出应用程序的槽函数
void MainWindow::quitApplication()
{
    // 在退出前正确隐藏并删除托盘图标和悬浮窗
    if (trayIcon) {
        trayIcon->hide();
    }
    
    if (floatingWindow) {
        floatingWindow->hide();
    }
    
    QApplication::quit();
}

// 添加系统托盘图标激活处理函数
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        // 单击托盘图标时显示/隐藏主窗口
        if (isVisible()) {
            hide();
        } else {
            showNormal();
            activateWindow();
        }
        break;
    default:
        break;
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - dragPosition);
        event->accept();
    }
}

// 添加事件过滤器实现悬浮窗拖拽
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    static QPoint dragStartPos;
    static bool dragging = false;

    if (obj == floatingWindow) {
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton) {
                dragStartPos = mouseEvent->globalPos() - floatingWindow->frameGeometry().topLeft();
                dragging = true;
                return true;
            }
        } else if (event->type() == QEvent::MouseMove) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (dragging && (mouseEvent->buttons() & Qt::LeftButton)) {
                QPoint newPos = mouseEvent->globalPos() - dragStartPos;
                floatingWindow->move(newPos);
                return true;
            }
        } else if (event->type() == QEvent::MouseButtonRelease) {
            dragging = false;
            return true;
        }
    }
    return QMainWindow::eventFilter(obj, event);
}

// 重写关闭事件，使窗口关闭时最小化到系统托盘
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon && trayIcon->isVisible()) {
        hide();
        event->ignore();
    } else {
        QMainWindow::closeEvent(event);
    }
}

void MainWindow::toggleSchedulerService(QLabel* statusLabel, QPushButton* toggleButton)
{
    // 实现服务切换逻辑
    QString serviceName = "cpu-scheduler.service";
    QString currentStatus = statusLabel->text();
    
    QProcess process;
    if (currentStatus == "运行中") {
        // 停止服务
        process.start("pkexec", QStringList() << "systemctl" << "stop" << serviceName);
    } else {
        // 启动服务
        process.start("pkexec", QStringList() << "systemctl" << "start" << serviceName);
    }
    
    process.waitForFinished();
    
    // 更新状态显示
    updateSchedulerStatus(statusLabel, toggleButton);
}

void MainWindow::resetCpuFrequency()
{
    // 恢复CPU最大频率
    CpuScheduler scheduler;
    if (scheduler.resetCpuFrequency()) {
        QMessageBox::information(this, "成功", "CPU频率已恢复到硬件支持的最大频率");
    } else {
        QMessageBox::warning(this, "错误", "恢复CPU频率失败");
    }
}

void MainWindow::applySchedulerConfig(QSpinBox* intervalSpin, QSpinBox* highFreqSpin, QSpinBox* lowFreqSpin,
                                      QSpinBox* highTempSpin, QSpinBox* lowTempSpin, QSpinBox* sustainedSpin,
                                      QSpinBox* reductionSpin, QSpinBox* increaseSpin, QSpinBox* minFreqLimitSpin,
                                      QCheckBox* tempControlCheckbox, QCheckBox* freqControlCheckbox)
{
    // 应用调度器配置
    QMessageBox msgBox;
    msgBox.setText("应用配置需要重启服务，是否继续？");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    
    if (msgBox.exec() == QMessageBox::Yes) {
        // 创建配置结构体
        SchedulerConfig config;
        config.checkInterval = intervalSpin->value();
        config.highFreqThreshold = highFreqSpin->value();
        config.lowFreqThreshold = lowFreqSpin->value();
        config.highTempThreshold = highTempSpin->value();
        config.lowTempThreshold = lowTempSpin->value();
        config.sustainedPeriod = sustainedSpin->value();
        config.freqReduction = reductionSpin->value();
        config.freqIncrease = increaseSpin->value();
        config.minFreqLimit = minFreqLimitSpin->value();
        config.enableTempControl = tempControlCheckbox->isChecked();
        config.enableFreqControl = freqControlCheckbox->isChecked();
        config.logFile = "/var/log/cpu-scheduler.log";
        config.configFile = "/etc/cpu-scheduler.conf";
        
        // 设置配置并保存
        CpuScheduler scheduler;  // 修复类名
        scheduler.setConfig(config);
        
        if (scheduler.createConfigFile()) {
            // 重启服务
            QProcess stopProcess;
            stopProcess.start("pkexec", QStringList() << "systemctl" << "stop" << "cpu-scheduler.service");
            stopProcess.waitForFinished();
            
            QProcess startProcess;
            startProcess.start("pkexec", QStringList() << "systemctl" << "start" << "cpu-scheduler.service");
            startProcess.waitForFinished();
            
            QMessageBox::information(this, "成功", "配置已应用，服务已重启");
        } else {
            QMessageBox::warning(this, "错误", "保存配置文件失败");
        }
    }
}

void MainWindow::resetSchedulerConfig(QSpinBox* intervalSpin, QSpinBox* highFreqSpin, QSpinBox* lowFreqSpin,
                                      QSpinBox* highTempSpin, QSpinBox* lowTempSpin, QSpinBox* sustainedSpin,
                                      QSpinBox* reductionSpin, QSpinBox* increaseSpin, QSpinBox* minFreqLimitSpin,
                                      QCheckBox* tempControlCheckbox, QCheckBox* freqControlCheckbox)
{
    // 恢复默认配置
    QMessageBox msgBox;
    msgBox.setText("是否重置所有配置为默认值，并重启服务应用默认配置？");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    
    if (msgBox.exec() == QMessageBox::Yes) {
        // 重置为默认值
        intervalSpin->setValue(10);
        highFreqSpin->setValue(80);
        lowFreqSpin->setValue(40);
        highTempSpin->setValue(60);
        lowTempSpin->setValue(40);
        sustainedSpin->setValue(60);
        reductionSpin->setValue(25);
        increaseSpin->setValue(25);
        minFreqLimitSpin->setValue(50);
        tempControlCheckbox->setChecked(true);
        freqControlCheckbox->setChecked(true);
        
        // 保存配置并重启服务
        saveSchedulerConfig(intervalSpin, highFreqSpin, lowFreqSpin, highTempSpin, lowTempSpin,
                            sustainedSpin, reductionSpin, increaseSpin, minFreqLimitSpin,
                            tempControlCheckbox, freqControlCheckbox);
        
        // 重启服务
        QProcess stopProcess;
        stopProcess.start("pkexec", QStringList() << "systemctl" << "stop" << "cpu-scheduler.service");
        stopProcess.waitForFinished();
        
        QProcess startProcess;
        startProcess.start("pkexec", QStringList() << "systemctl" << "start" << "cpu-scheduler.service");
        startProcess.waitForFinished();
        
        QMessageBox::information(this, "成功", "配置已重置，服务已重启");
    }
}

void MainWindow::saveSchedulerConfig(QSpinBox* intervalSpin, QSpinBox* highFreqSpin, QSpinBox* lowFreqSpin,
                                     QSpinBox* highTempSpin, QSpinBox* lowTempSpin, QSpinBox* sustainedSpin,
                                     QSpinBox* reductionSpin, QSpinBox* increaseSpin, QSpinBox* minFreqLimitSpin,
                                     QCheckBox* tempControlCheckbox, QCheckBox* freqControlCheckbox)
{
    // 保存调度器配置
    SchedulerConfig config;
    config.checkInterval = intervalSpin->value();
    config.highFreqThreshold = highFreqSpin->value();
    config.lowFreqThreshold = lowFreqSpin->value();
    config.highTempThreshold = highTempSpin->value();
    config.lowTempThreshold = lowTempSpin->value();
    config.sustainedPeriod = sustainedSpin->value();
    config.freqReduction = reductionSpin->value();
    config.freqIncrease = increaseSpin->value();
    config.minFreqLimit = minFreqLimitSpin->value();
    config.enableTempControl = tempControlCheckbox->isChecked();
    config.enableFreqControl = freqControlCheckbox->isChecked();
    config.logFile = "/var/log/cpu-scheduler.log";
    config.configFile = "/etc/cpu-scheduler.conf";
    
    // 设置配置并保存
    CpuScheduler scheduler;  // 修复类名
    scheduler.setConfig(config);
    
    if (scheduler.createConfigFile()) {
        QMessageBox::information(this, "成功", "配置已保存到 /etc/cpu-scheduler.conf");
    } else {
        QMessageBox::warning(this, "错误", "保存配置文件失败");
    }
}

void MainWindow::updateSchedulerStatus(QLabel* statusLabel, QPushButton* toggleButton)
{
    // 更新调度器服务状态
    QProcess process;
    process.start("systemctl", QStringList() << "is-active" << "cpu-scheduler.service");
    process.waitForFinished();
    
    QString status = process.readAllStandardOutput().trimmed();
    if (status == "active") {
        statusLabel->setText("运行中");
        statusLabel->setStyleSheet("QLabel { color : green; font-weight: bold; }");
        toggleButton->setText("停止服务");
    } else {
        statusLabel->setText("已停止");
        statusLabel->setStyleSheet("QLabel { color : red; font-weight: bold; }");
        toggleButton->setText("启动服务");
    }
}
